package world;

import java.nio.FloatBuffer;

import opengl.texture.Texture;
import opengl.texture.TextureLoader;

import org.lwjgl.BufferUtils;
import org.lwjgl.opengl.GL11;
import org.lwjgl.opengl.GL13;
import org.lwjgl.opengl.GL15;
import org.lwjgl.opengl.GL20;

import sys.SysParam;

public class Crosshair {
	private static TextureLoader textureManager = TextureLoader.get();
	private Texture texture;
	private FloatBuffer verticesBuffer;
	private Vertex[] vertexes = new Vertex[6];

	public Crosshair() {
	}

	public void createVertexes(float x, float y, float w, float h) {
		// front
		int i = 0;
		float zPostion =-100.0f;
		x=0;
		y=0;
		w=4;
		h=3f;
				
		vertexes[i++] = new Vertex().setXYZ(x, y + h, zPostion).setRGB(1, 0, 0).setST(0, 0);
		vertexes[i++] = new Vertex().setXYZ(x + w, y + h, zPostion).setRGB(1, 1, 1).setST(1, 0);	
		vertexes[i++] = new Vertex().setXYZ(x + w, y, zPostion).setRGB(0, 0, 1).setST(1, 1);
		vertexes[i++] = new Vertex().setXYZ(x, y, zPostion).setRGB(0, 1, 0).setST(0, 1);
	}

	public void buildRenderData() {
		verticesBuffer = BufferUtils.createFloatBuffer(4* Vertex.SIZE_ALL);
		for (int i = 0; i < 4; i++) {// 6 vertexes
			verticesBuffer.put(vertexes[i].getElements());
		}
		verticesBuffer.flip();
	}

	public void render() {
		if (texture == null) {
			setupTexture();
			int crossX = (int) (SysParam.SCREEN_WIDTH / 2 - texture.getImageWidth() / 2);
			int crossY = (int) (SysParam.SCREEN_HEIGHT / 2 - texture.getImageHeight() / 2);
			createVertexes(crossX, crossY,1, 1);
			buildRenderData();
		}

		GL13.glActiveTexture(GL13.GL_TEXTURE0);
		GL11.glBindTexture(GL11.GL_TEXTURE_2D, texture.getTextureID());
		// Bind to the VAO that has all the information about the vertices
		GL20.glEnableVertexAttribArray(0);
		GL20.glEnableVertexAttribArray(1);
		GL20.glEnableVertexAttribArray(2);

		renderBuffer();

		GL20.glDisableVertexAttribArray(0);
		GL20.glDisableVertexAttribArray(1);
		GL20.glDisableVertexAttribArray(2);
		GL11.glBindTexture(GL11.GL_TEXTURE_2D, 0);
	}

	private void renderBuffer() {
		int vboId = GL15.glGenBuffers();
		GL15.glBindBuffer(GL15.GL_ARRAY_BUFFER, vboId);
		GL15.glBufferData(GL15.GL_ARRAY_BUFFER, verticesBuffer, GL15.GL_STATIC_DRAW);

		GL20.glVertexAttribPointer(0, Vertex.SIZE_POSITION, GL11.GL_FLOAT, false, Vertex.STRIDE, Vertex.OFFSET_POSITION);
		GL20.glVertexAttribPointer(1, Vertex.SIZE_COLOR, GL11.GL_BYTE, false, Vertex.STRIDE, Vertex.OFFSET_COLOR);
		GL20.glVertexAttribPointer(2, Vertex.SIZE_TEXTURE, GL11.GL_FLOAT, false, Vertex.STRIDE, Vertex.OFFSET_TEXTURE);
		GL11.glDrawArrays(GL11.GL_QUADS, 0, 6);

		GL15.glBindBuffer(GL15.GL_ARRAY_BUFFER, 0);
		GL15.glDeleteBuffers(vboId);// this is very important to release the
									// memory
	}

	private void setupTexture() {
		texture = textureManager.getTexture("assets/images/crosshair.png", false);
	}
}